const plist = require('plist')
var fs = require('fs');
var Jimp = require('jimp');
//开始时间
var startTime = new Date().getTime();
//读取文件内容 , 用 plist 转内容为 Js 对象
var fileContent = fs.readFileSync(__dirname + '/common.plist', 'utf8');
//内容转换
var content = plist.parse(fileContent);
var number = 0;
var imgNameArr = new Array();
var textureRectArr = new Array();
for (let imgName in content['frames']) {
  imgNameArr.push(imgName);
  number++;
}
//string转obj
for (let i = 0; i < imgNameArr.length; i++) {
  let textureRect = content['frames'][imgNameArr[i]].textureRect;
  let temp = textureRect.slice(2, textureRect.length - 2);
  let temp2 = temp.split("},{");
  let pos = temp2[0].split(",");
  let size = temp2[1].split(",");
  let rect = {
    'x': Number(pos[0]),
    'y': Number(pos[1]),
    'h': Number(size[1]),
    'w': Number(size[0]),
  }
  textureRectArr.push(rect);
}
//图片裁剪 crop( x, y, w, h)
async function crop(x, y, w, h, name, fun) {
  // 读取图片
  var image = await Jimp.read(__dirname + '/common.png');
  await image.crop(x, y, w, h);
  // 保存 
  await image.writeAsync(name).then(fun());
}
//更具plist文件实现图片裁剪
for (let i = 0; i < number; i++) {
  var name = __dirname + "/imgs/" + imgNameArr[i];
  crop(textureRectArr[i].x, textureRectArr[i].y, textureRectArr[i].w, textureRectArr[i].h, name, () => {
    if (i >= number - 1) {
      //打印日志
      let time = ((new Date().getTime() - startTime) / 1000).toFixed(2);
      console.log("裁剪完成,文件路径" + __dirname + "/imgs文件夹下,本次耗时" + time + "秒");
    }
  });
}
